package com.sxfq.loansupermarket.backsystem.modular.arrival.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.CommUtils;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.dao.CustomerDao;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ApprovalProcessInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchCustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.UserInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class CustomerServiceImpl implements ICustomerService {

    @Autowired
    private CustomerDao dao;

    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    IReservationsService reservationsService;

    @Override
    public List<CustomerInfo> selectPageListByQueryGetMap(Page<CustomerInfo> page, SearchCustomerInfo searchInfo) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String table1 = tableHead + "deal_info";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            params.put("reach", searchInfo.getReach());
        }
        if (StringUtil.isNotEmpty(searchInfo.getCustomerName())) {
            params.put("customerName", searchInfo.getCustomerName());
        }
        if (StringUtil.isNotEmpty(searchInfo.getCustomerPhone())) {
            params.put("customerPhone", searchInfo.getCustomerPhone());
        }
        if (StringUtil.isNotEmpty(searchInfo.getDealStatus())) {
            if ("已成交".equals(searchInfo.getDealStatus())) {
                params.put("dealStatus", "t.deal_status ='已成交'");
            } else {
                params.put("dealStatus", "t.deal_status !='已成交'");
            }
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartArrivalTime())) {
            params.put("startArrivalTime", searchInfo.getStartArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndArrivalTime())) {
            params.put("endArrivalTime", searchInfo.getEndArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getReservations())) {
            params.put("reservations", searchInfo.getReservations());
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartRevisitTime())) {
            params.put("startRevisitTime", searchInfo.getStartRevisitTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndRevisitTime())) {
            params.put("endRevisitTime", searchInfo.getEndRevisitTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getIsReturnVisit())) {
            params.put("isReturnVisit", searchInfo.getIsReturnVisit());
        }
        if (StringUtil.isNotEmpty(searchInfo.getFieldTc())) {
            params.put("fieldTc", searchInfo.getFieldTc());
        }
        if (StringUtil.isNotEmpty(searchInfo.getDoctor())) {
            params.put("doctor", searchInfo.getDoctor());
        }
        if (StringUtil.isNotEmpty(searchInfo.getXcustomerStatus())) {
            params.put("xcustomerStatus", " in ("+(searchInfo.getXcustomerStatus()).replace("& #39;","'")+")");
        }
        if (StringUtil.isNotEmpty(searchInfo.getAppointmentPayService())) {
            String appointmentPayService = "";
            String appointmentPayServices[] = searchInfo.getAppointmentPayService().split(",");
            if (appointmentPayServices.length == 1) {
                appointmentPayService = appointmentPayServices[0];
            } else {
                for (int i = 0; i < appointmentPayServices.length; i++) {
                    if (i == (appointmentPayServices.length - 1)) {
                        appointmentPayService += "'" + appointmentPayServices[i];
                    } else if (i == 0) {
                        appointmentPayService += appointmentPayServices[i] + "'" + ",";
                    } else {
                        appointmentPayService += "'" + appointmentPayServices[i] + "'" + ",";
                    }
                }
            }
            params.put("appointmentPayService", " t.appointment_pay_service in ('" + appointmentPayService + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getOneChannel()) && !"请选择".equals(searchInfo.getOneChannel())) {
            String oneChannel = "";
            String oneChannel2[] = searchInfo.getOneChannel().split(",");
            if (oneChannel2.length == 1) {
                oneChannel = oneChannel2[0];
            } else {
                for (int i = 0; i < oneChannel2.length; i++) {
                    if (i == (oneChannel2.length - 1)) {
                        oneChannel += "'" + oneChannel2[i];
                    } else if (i == 0) {
                        oneChannel += oneChannel2[i] + "'" + ",";
                    } else {
                        oneChannel += "'" + oneChannel2[i] + "'" + ",";
                    }
                }
            }
            params.put("oneChannel", " t.one_channel in ('" + oneChannel + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getTwoChannel()) && !"请选择".equals(searchInfo.getTwoChannel())) {
            String twoChannel = "";
            String twoChannel2[] = searchInfo.getTwoChannel().split(",");
            if (twoChannel2.length == 1) {
                twoChannel = twoChannel2[0];
            } else {
                for (int i = 0; i < twoChannel2.length; i++) {
                    if (i == (twoChannel2.length - 1)) {
                        twoChannel += "'" + twoChannel2[i];
                    } else if (i == 0) {
                        twoChannel += twoChannel2[i] + "'" + ",";
                    } else {
                        twoChannel += "'" + twoChannel2[i] + "'" + ",";
                    }
                }
            }
            params.put("twoChannel", " t.two_channel in ('" + twoChannel + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getThrChannel()) && !"请选择".equals(searchInfo.getThrChannel())) {
            String thrChannel = "";
            String thrChannel2[] = searchInfo.getThrChannel().split(",");
            if (thrChannel2.length == 1) {
                thrChannel = thrChannel2[0];
            } else {
                for (int i = 0; i < thrChannel2.length; i++) {
                    if (i == (thrChannel2.length - 1)) {
                        thrChannel += "'" + thrChannel2[i];
                    } else if (i == 0) {
                        thrChannel += thrChannel2[i] + "'" + ",";
                    } else {
                        thrChannel += "'" + thrChannel2[i] + "'" + ",";
                    }
                }
            }
            params.put("thrChannel", " t.thr_channel in ('" + thrChannel + "')");
        }
        params.put("tableName", this.getTableName());
        params.put("table1", table1);
        params.put("startIndex", searchInfo.getStartIndex());
        params.put("limitIndex", searchInfo.getLimitIndex());
        return dao.getQueryPage(page, params);
    }

    public int getQueryPagesCount(Page<CustomerInfo> page, SearchCustomerInfo searchInfo) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String table1 = tableHead + "deal_info";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            params.put("reach", searchInfo.getReach());
        }
        if (StringUtil.isNotEmpty(searchInfo.getCustomerName())) {
            params.put("customerName", searchInfo.getCustomerName());
        }
        if (StringUtil.isNotEmpty(searchInfo.getCustomerPhone())) {
            params.put("customerPhone", searchInfo.getCustomerPhone());
        }
        if (StringUtil.isNotEmpty(searchInfo.getDealStatus())) {
            if ("已成交".equals(searchInfo.getDealStatus())) {
                params.put("dealStatus", "t.deal_status ='已成交'");
            } else {
                params.put("dealStatus", "t.deal_status !='已成交'");
            }
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartArrivalTime())) {
            params.put("startArrivalTime", searchInfo.getStartArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndArrivalTime())) {
            params.put("endArrivalTime", searchInfo.getEndArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getReservations())) {
            params.put("reservations", searchInfo.getReservations());
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartRevisitTime())) {
            params.put("startRevisitTime", searchInfo.getStartRevisitTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndRevisitTime())) {
            params.put("endRevisitTime", searchInfo.getEndRevisitTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getIsReturnVisit())) {
            params.put("isReturnVisit", searchInfo.getIsReturnVisit());
        }
        if (StringUtil.isNotEmpty(searchInfo.getFieldTc())) {
            params.put("fieldTc", searchInfo.getFieldTc());
        }
        if (StringUtil.isNotEmpty(searchInfo.getDoctor())) {
            params.put("doctor", searchInfo.getDoctor());
        }
        if (StringUtil.isNotEmpty(searchInfo.getXcustomerStatus())) {
            params.put("xcustomerStatus", " in ("+(searchInfo.getXcustomerStatus()).replace("& #39;","'")+")");
        }
        if (StringUtil.isNotEmpty(searchInfo.getAppointmentPayService())) {
            String appointmentPayService = "";
            String appointmentPayServices[] = searchInfo.getAppointmentPayService().split(",");
            if (appointmentPayServices.length == 1) {
                appointmentPayService = appointmentPayServices[0];
            } else {
                for (int i = 0; i < appointmentPayServices.length; i++) {
                    if (i == (appointmentPayServices.length - 1)) {
                        appointmentPayService += "'" + appointmentPayServices[i];
                    } else if (i == 0) {
                        appointmentPayService += appointmentPayServices[i] + "'" + ",";
                    } else {
                        appointmentPayService += "'" + appointmentPayServices[i] + "'" + ",";
                    }
                }
            }
            params.put("appointmentPayService", " t.appointment_pay_service in ('" + appointmentPayService + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getOneChannel()) && !"请选择".equals(searchInfo.getOneChannel())) {
            String oneChannel = "";
            String oneChannel2[] = searchInfo.getOneChannel().split(",");
            if (oneChannel2.length == 1) {
                oneChannel = oneChannel2[0];
            } else {
                for (int i = 0; i < oneChannel2.length; i++) {
                    if (i == (oneChannel2.length - 1)) {
                        oneChannel += "'" + oneChannel2[i];
                    } else if (i == 0) {
                        oneChannel += oneChannel2[i] + "'" + ",";
                    } else {
                        oneChannel += "'" + oneChannel2[i] + "'" + ",";
                    }
                }
            }
            params.put("oneChannel", " t.one_channel in ('" + oneChannel + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getTwoChannel()) && !"请选择".equals(searchInfo.getTwoChannel())) {
            String twoChannel = "";
            String twoChannel2[] = searchInfo.getTwoChannel().split(",");
            if (twoChannel2.length == 1) {
                twoChannel = twoChannel2[0];
            } else {
                for (int i = 0; i < twoChannel2.length; i++) {
                    if (i == (twoChannel2.length - 1)) {
                        twoChannel += "'" + twoChannel2[i];
                    } else if (i == 0) {
                        twoChannel += twoChannel2[i] + "'" + ",";
                    } else {
                        twoChannel += "'" + twoChannel2[i] + "'" + ",";
                    }
                }
            }
            params.put("twoChannel", " t.two_channel in ('" + twoChannel + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getThrChannel()) && !"请选择".equals(searchInfo.getThrChannel())) {
            String thrChannel = "";
            String thrChannel2[] = searchInfo.getThrChannel().split(",");
            if (thrChannel2.length == 1) {
                thrChannel = thrChannel2[0];
            } else {
                for (int i = 0; i < thrChannel2.length; i++) {
                    if (i == (thrChannel2.length - 1)) {
                        thrChannel += "'" + thrChannel2[i];
                    } else if (i == 0) {
                        thrChannel += thrChannel2[i] + "'" + ",";
                    } else {
                        thrChannel += "'" + thrChannel2[i] + "'" + ",";
                    }
                }
            }
            params.put("thrChannel", " t.thr_channel in ('" + thrChannel + "')");
        }
        params.put("tableName", this.getTableName());
        params.put("table1", table1);
        return dao.getQueryPagesCount(page, params);
    }

    @Override
    public List<CustomerInfo> customerExport(SearchCustomerInfo searchInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtil.isNotEmpty(searchInfo.getReach())) {
            params.put("reach", searchInfo.getReach());
        }
        if (StringUtil.isNotEmpty(searchInfo.getCustomerName())) {
            params.put("customerName", searchInfo.getCustomerName());
        }
        if (StringUtil.isNotEmpty(searchInfo.getCustomerPhone())) {
            params.put("customerPhone", searchInfo.getCustomerPhone());
        }
        if (StringUtil.isNotEmpty(searchInfo.getDealStatus())) {
            if ("已成交".equals(searchInfo.getDealStatus())) {
                params.put("dealStatus", "t2.deal_status ='已成交'");
            } else {
                params.put("dealStatus", "t2.deal_status !='已成交'");
            }
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartArrivalTime())) {
            params.put("startArrivalTime", searchInfo.getStartArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndArrivalTime())) {
            params.put("endArrivalTime", searchInfo.getEndArrivalTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getReservations())) {
            params.put("reservations", searchInfo.getReservations());
        }
        if (StringUtil.isNotEmpty(searchInfo.getStartRevisitTime())) {
            params.put("startRevisitTime", searchInfo.getStartRevisitTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getEndRevisitTime())) {
            params.put("endRevisitTime", searchInfo.getEndRevisitTime());
        }
        if (StringUtil.isNotEmpty(searchInfo.getIsReturnVisit())) {
            params.put("isReturnVisit", searchInfo.getIsReturnVisit());
        }
        if (StringUtil.isNotEmpty(searchInfo.getFieldTc())) {
            params.put("fieldTc", searchInfo.getFieldTc());
        }
        if (StringUtil.isNotEmpty(searchInfo.getDoctor())) {
            params.put("doctor", searchInfo.getDoctor());
        }
        if (StringUtil.isNotEmpty(searchInfo.getXcustomerStatus())) {
            params.put("xcustomerStatus", " in ("+(searchInfo.getXcustomerStatus()).replace("& #39;","'")+")");
        }
        if (StringUtil.isNotEmpty(searchInfo.getAppointmentPayService())) {
            String appointmentPayService = "";
            String appointmentPayServices[] = searchInfo.getAppointmentPayService().split(",");
            if (appointmentPayServices.length == 1) {
                appointmentPayService = appointmentPayServices[0];
            } else {
                for (int i = 0; i < appointmentPayServices.length; i++) {
                    if (i == (appointmentPayServices.length - 1)) {
                        appointmentPayService += "'" + appointmentPayServices[i];
                    } else if (i == 0) {
                        appointmentPayService += appointmentPayServices[i] + "'" + ",";
                    } else {
                        appointmentPayService += "'" + appointmentPayServices[i] + "'" + ",";
                    }
                }
            }
            params.put("appointmentPayService", " t2.appointment_pay_service in ('" + appointmentPayService + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getOneChannel())) {
            String oneChannel = "";
            String oneChannel2[] = searchInfo.getOneChannel().split(",");
            if (oneChannel2.length == 1) {
                oneChannel = oneChannel2[0];
            } else {
                for (int i = 0; i < oneChannel2.length; i++) {
                    if (i == (oneChannel2.length - 1)) {
                        oneChannel += "'" + oneChannel2[i];
                    } else if (i == 0) {
                        oneChannel += oneChannel2[i] + "'" + ",";
                    } else {
                        oneChannel += "'" + oneChannel2[i] + "'" + ",";
                    }
                }
            }
            params.put("oneChannel", " t2.one_channel in ('" + oneChannel + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getTwoChannel())) {
            String twoChannel = "";
            String twoChannel2[] = searchInfo.getTwoChannel().split(",");
            if (twoChannel2.length == 1) {
                twoChannel = twoChannel2[0];
            } else {
                for (int i = 0; i < twoChannel2.length; i++) {
                    if (i == (twoChannel2.length - 1)) {
                        twoChannel += "'" + twoChannel2[i];
                    } else if (i == 0) {
                        twoChannel += twoChannel2[i] + "'" + ",";
                    } else {
                        twoChannel += "'" + twoChannel2[i] + "'" + ",";
                    }
                }
            }
            params.put("twoChannel", " t2.two_channel in ('" + twoChannel + "')");
        }
        if (StringUtil.isNotEmpty(searchInfo.getThrChannel())) {
            String thrChannel = "";
            String thrChannel2[] = searchInfo.getThrChannel().split(",");
            if (thrChannel2.length == 1) {
                thrChannel = thrChannel2[0];
            } else {
                for (int i = 0; i < thrChannel2.length; i++) {
                    if (i == (thrChannel2.length - 1)) {
                        thrChannel += "'" + thrChannel2[i];
                    } else if (i == 0) {
                        thrChannel += thrChannel2[i] + "'" + ",";
                    } else {
                        thrChannel += "'" + thrChannel2[i] + "'" + ",";
                    }
                }
            }
            params.put("thrChannel", " t2.thr_channel in ('" + thrChannel + "')");
        }
        params.put("tableName", this.getTableName());
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName1 = tableHead + "recharge_info";
        String tableName3 = tableHead + "deal_info";
        params.put("tableName1", tableName1);
        params.put("tableName3", tableName3);
        return dao.getQueryPages(params);
    }


    public CustomerInfo selectOneById(String customerId) {
        String sql = "select * from " + this.getTableName() + " where id= '" + customerId + "';";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        return customerInfo;
    }

    public CustomerInfo selectOneByReservationsId(String reservationsId) {
        String sql = "select * from " + this.getTableName() + " where reservations_id= '" + reservationsId + "' order by arrival_time desc limit 0,1;";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        return customerInfo;
    }

    public String getCustomerStatus(CustomerInfo customerInfo) {
        String sql1 = " select * from " + this.getTableName() + " a where a.first_visit_date<DATE_SUB(curdate(),INTERVAL 0 DAY)" +
                " and a.reservations_id='" + customerInfo.getReservationsId() + "' and (a.arrival_status!=1 or a.arrival_status is null or a.arrival_status ='');";
        List<CustomerInfo> list1 = sqlMapper.selectList(sql1, CustomerInfo.class);
        if (list1.size() > 0) {
            String sql2 = "SELECT *,COUNT(CASE a.deal_status WHEN '已成交' THEN 0 END) AS consumption\n" +
                    "from " + this.getTableName() + " a where a.first_visit_date<=DATE_SUB(curdate(),INTERVAL 0 DAY)\n" +
                    "and a.reservations_id='" + customerInfo.getReservationsId() + "' and (a.arrival_status!=1 or a.arrival_status is null or a.arrival_status ='') group by a.reservations_id\n" +
                    "HAVING consumption>0";
            List<CustomerInfo> list2 = sqlMapper.selectList(sql2, CustomerInfo.class);
            if (list2.size() > 0) {
                return "复诊";
            } else {
                return "新客二次";
            }
        } else {
            return "新客首次";
        }
    }

    public int insert(CustomerInfo info) {
        String id = CommUtils.getUUID();
        String tableHead = ShiroKit.getUser().getAbbreviation();
        id = id + tableHead;
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        id = id + randomNumber;
        String filingTime = "";
        String birthday = "";
        String auditorTime = "";
        String phoneSharShip = "";
        if (info.getFilingTime() == null || info.getFilingTime() == "") {
            filingTime = "null";
        } else {
            filingTime = "'" + info.getFilingTime() + "'";
        }
        if (info.getBirthday() == null || info.getBirthday() == "") {
            birthday = "null";
        } else {
            birthday = "'" + info.getBirthday() + "'";
        }
        if (info.getAuditorTime() == null || info.getAuditorTime() == "") {
            auditorTime = "null";
        } else {
            auditorTime = "'" + info.getAuditorTime() + "'";
        }
        if (info.getPhoneSharShip() == null || info.getPhoneSharShip() == "") {
            phoneSharShip = "'本人'";
        } else {
            phoneSharShip = "'" + info.getPhoneSharShip() + "'";
        }
        if (info.getCustomerAge() != null) {
            for (int i = 0; i < 11; i++) {
                if (info.getCustomerAge() >= (i * 10) && info.getCustomerAge() <= (i * 10 + 9)) {
                    if (i < 10) {
                        String ageRange = (i * 10) + "-" + (i * 10 + 9);
                        info.setAgeRange(ageRange);
                    } else {
                        String ageRange = "99+";
                        info.setAgeRange(ageRange);
                    }
                }
            }
        }
        Calendar now = Calendar.getInstance();
        Map<String, Object> params = new HashMap<String, Object>();
        String month = "";
        String dayOfMonth = "";
        if ((now.get(Calendar.MONTH) + 1) < 10) {
            month = "0" + (now.get(Calendar.MONTH) + 1);
        } else {
            month = (now.get(Calendar.MONTH) + 1) + "";
        }
        if ((now.get(Calendar.DAY_OF_MONTH)) < 10) {
            dayOfMonth = "0" + (now.get(Calendar.DAY_OF_MONTH)) + "";
        } else {
            dayOfMonth = (now.get(Calendar.DAY_OF_MONTH)) + "";
        }
        params.put("tableName", this.getTableName());
        String year = now.get(Calendar.YEAR) + "";
        String abbreviation = ShiroKit.getUser().getAbbreviation() + "";
        params.put("medicalRecordNumber", abbreviation.substring(3, abbreviation.length() - 1) + year.substring(2, 4) + month + dayOfMonth);
        int customerCount = dao.getCount(params);
        String customerCounts = customerCount + 1 + "";
        if (customerCount < 10) {
            customerCounts = "00" + customerCounts;
        } else if (customerCount >= 10 && customerCount < 100) {
            customerCounts = "0" + customerCounts;
        } else {
            customerCounts = "" + customerCounts;
        }
        info.setMedicalRecordNumber(abbreviation.substring(3, abbreviation.length() - 1) + year.substring(2, 4) + month + dayOfMonth + customerCounts);
        info.setArrivalStore(ShiroKit.getUser().getOutpatientName());
        String selectSql = "select * from " + this.getTableName() + " where reservations_id='" + info.getReservationsId() + "' limit 0,1";
        CustomerInfo info1 = sqlMapper.selectOne(selectSql, CustomerInfo.class);
        Double actualAccountBalance = 0.00;
        Double giveAccountBalance = 0.00;
        Double accountArrears = 0.00;
        if (info1 != null) {
            actualAccountBalance = info1.getActualAccountBalance();
            giveAccountBalance = info1.getGiveAccountBalance();
            accountArrears = info1.getAccountArrears();
        }
        if (info.getArchiving() == "" || info.getArchiving() == null) {
            info.setArchiving(ShiroKit.getUser().getAccount());
        }
        info.setStatus("到店");
        info.setDiagnosisStatus("未看诊");
        info.setDealStatus("未开单");
        //设置开始时间
        String starttime = DateTimeKit.now();
        String time = starttime.substring(0, 11);
        int hour = Integer.parseInt(starttime.substring(11, 13));
        int minute = Integer.parseInt(starttime.substring(14, 16));
        //String second=starttime.substring(17,19);
        minute = (minute / 15) * 15;
        String minutes = minute + "";
        if ("0".equals(minutes)) {
            minutes = "00";
        }
        starttime = time + hour + ":" + minutes + ":00";
        info.setStartTime(starttime);
        String endtime = "";
        if (hour + 1 == 24) {
            time = time.substring(0, 9) + (Integer.parseInt(time.substring(9, 10)) + 1) + " ";
            endtime = time + "00" + ":" + minutes + ":00";
        } else {
            endtime = time + (hour + 1) + ":" + minutes + ":00";
        }
        info.setEndTime(endtime);
        if (info.getDoctor() == "" || info.getDoctor() == null) {
            info.setDoctor("未指定医生");
        }
        if (info.getAddress() == "" || info.getAddress() == null) {
            info.setAddress("");
        }
        //设置黄页编号
        String sql1 = " select max(yellow_number) as yellowNumber from " + this.getTableName() + " ";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
        Integer yellowNumbers = 4396;
        if (customerInfo != null) {
            yellowNumbers = Integer.parseInt(customerInfo.getYellowNumber()) + 1;
        }
        if ("null".equals(info.getOtherContact()) || info.getOtherContact() == null) {
            info.setOtherContact("");
        }
        String sql = "INSERT INTO `" + this.getTableName() + "` (`id`,`first_visit_date`,`actual_account_balance`,`department`,`give_account_balance`,`account_arrears`,`age_range`,`reservations_id`,`appointment_pay_service`,`arrival_store`,`phone_shar_ship`,`deal_status`, `customer_name`, `pseudonym`, `customer_phone`, " +
                "`one_medium`,`two_medium`,`thr_medium`, `one_channel`,`two_channel`,`thr_channel`," +
                "`field_tc`, `customer_sex`, `customer_age`, `birthday`," +
                " `address`, `referee`, `referee_ship`, `id_card_no`," +
                " `fixed_telephone`, `is_have_children`, `email`, `zip_code`, " +
                "`customer_status`, `number_of_audits`, `auditor_time`, `final_auditor`," +
                "  `non_transaction_level`, `transaction_level`, `characters`, " +
                "`consumption_habits`, `is_return_visit`, `cause_of_no_return_visit`, `consum_ability`," +
                " `qq_number`, `wechat_number`, `other_contact`, `country`," +
                " `province`, `cities`, `region`, `medical_record_number`, " +
                " `marital_status`, `occupation`, `archiving`, `entry_clerk`,`update_people`,`update_time`," +
                " `filing_time`, `arrival_time`, `remarks`, `status`, `diagnosis_status`,`arrival_status`,`doctor`,`start_time`,`end_time`," +
                "`create_appointment_time`,yellow_number,xcustomer_status) VALUES" +
                "('" + id + "','" + DateTimeKit.now() + "'," + actualAccountBalance + ",'"+info.getDepartment()+ "'," + giveAccountBalance + "," + accountArrears + ",'" + info.getAgeRange() + "','" + info.getReservationsId() + "','" + info.getAppointmentPayService() + "','" + info.getArrivalStore() + "'," + phoneSharShip + ",'" + info.getDealStatus() + "','" + info.getCustomerName().trim() + "','" + info.getPseudonym() +
                "','" + info.getCustomerPhone() + "','" + info.getOneMedium() + "','" + info.getTwoMedium() + "','" + info.getThrMedium() + "','" + info.getOneChannel() + "'" +
                ",'" + info.getTwoChannel() + "','" + info.getThrChannel() + "'" +
                ",'" + info.getFieldTc() + "'," + info.getCustomerSex() + "," + info.getCustomerAge() + "," + birthday +
                ",'" + info.getAddress() + "','" + info.getReferee() + "','" + info.getRefereeShip() + "','" + info.getIdCardNo() +
                "','" + info.getFixedTelephone() + "'," + info.getIsHaveChildren() + "," + "'" + info.getEmail() + "','" + info.getZipCode() +
                "','" + info.getCustomerStatus() + "'," + info.getNumberOfAudits() + "," + auditorTime + ",'" + info.getFinalAuditor() +
                "','" + info.getNonTransactionLevel() + "', '" + info.getTransactionLevel() + "','" + info.getCharacters() +
                "','" + info.getConsumptionHabits() + "'," + info.getIsReturnVisit() + ",'" + info.getCauseOfNoReturnVisit() + "','" + info.getConsumAbility() +
                "','" + info.getQqNumber() + "', '" + info.getWechatNumber() + "','" + info.getOtherContact() + "','" + info.getCountry() +
                "','" + info.getProvince() + "' ,'" + info.getCities() + "','" + info.getRegion() + "','" + info.getMedicalRecordNumber() + "','" + info.getMaritalStatus() + "'," +
                "'" + info.getOccupation() + "','" + info.getArchiving() + "','" + ShiroKit.getUser().getAccount() +
                "','" + ShiroKit.getUser().getAccount() + "'," + filingTime + "," + filingTime + "," +filingTime+ "" +
                ",'" + info.getRemarks() + "','" + info.getStatus() + "','" + info.getDiagnosisStatus() + "','2','" + info.getDoctor() + "','"
                + info.getStartTime() + "','" + info.getEndTime() + "','" + DateTimeKit.now() + "','" + yellowNumbers + "','" + info.getXcustomerStatus() + "');";
        return sqlMapper.insert(sql);
    }

    public String getMedicalRecordNumber() {
        String abbreviation = ShiroKit.getUser().getAbbreviation() + "";
        Map<String, Object> params = new HashMap<String, Object>();
        Calendar now = Calendar.getInstance();
        String year = now.get(Calendar.YEAR) + "";
        String month = "";
        String dayOfMonth = "";
        if ((now.get(Calendar.MONTH) + 1) < 10) {
            month = "0" + (now.get(Calendar.MONTH) + 1);
        } else {
            month = (now.get(Calendar.MONTH) + 1) + "";
        }
        if ((now.get(Calendar.DAY_OF_MONTH)) < 10) {
            dayOfMonth = "0" + (now.get(Calendar.DAY_OF_MONTH)) + "";
        } else {
            dayOfMonth = (now.get(Calendar.DAY_OF_MONTH)) + "";
        }
        params.put("tableName", this.getTableName());
        params.put("medicalRecordNumber", abbreviation.substring(3, abbreviation.length() - 1) + year.substring(2, 4) + month + dayOfMonth);
        int customerCount = dao.getCount(params);
        String customerCounts = customerCount + 1 + "";
        if (customerCount < 10) {
            customerCounts = "00" + customerCounts;
        } else if (customerCount >= 10 && customerCount < 100) {
            customerCounts = "0" + customerCounts;
        } else {
            customerCounts = "" + customerCounts;
        }
        return abbreviation.substring(3, abbreviation.length() - 1) + year.substring(2, 4) + month + dayOfMonth + customerCounts;
    }

    public String insert2(CustomerInfo info) {
        String id = CommUtils.getUUID();
        String tableHead = ShiroKit.getUser().getAbbreviation();
        id = id + tableHead;
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        id = id + randomNumber;
        String birthday = "";
        String auditorTime = "";
        String phoneSharShip = "";
        if (info.getBirthday() == null || info.getBirthday() == "") {
            birthday = "null";
        } else {
            birthday = "'" + info.getBirthday() + "'";
        }
        if (info.getAuditorTime() == null || info.getAuditorTime() == "") {
            auditorTime = "null";
        } else {
            auditorTime = "'" + info.getAuditorTime() + "'";
        }
        if (info.getPhoneSharShip() == null || info.getPhoneSharShip() == "") {
            phoneSharShip = "'本人'";
        } else {
            phoneSharShip = "'" + info.getPhoneSharShip() + "'";
        }
        //查询已有手机号的预约集合
        List<ReservationsInfo> existList = reservationsService.getCustomerPhoneCounts(info.getCustomerPhone());
        int count = existList.size();
        if (!"'本人'".equals(phoneSharShip)) {
            info.setCustomerPhone(info.getCustomerPhone() + "+" + count);
        }
        if (info.getCustomerAge() != null) {
            for (int i = 0; i < 11; i++) {
                if (info.getCustomerAge() >= (i * 10) && info.getCustomerAge() <= (i * 10 + 9)) {
                    if (i < 10) {
                        String ageRange = (i * 10) + "-" + (i * 10 + 9);
                        info.setAgeRange(ageRange);
                    } else {
                        String ageRange = "99+";
                        info.setAgeRange(ageRange);
                    }
                }
            }
        }
        Calendar now = Calendar.getInstance();
        Map<String, Object> params = new HashMap<String, Object>();
        String month = "";
        String dayOfMonth = "";
        if ((now.get(Calendar.MONTH) + 1) < 10) {
            month = "0" + (now.get(Calendar.MONTH) + 1);
        } else {
            month = (now.get(Calendar.MONTH) + 1) + "";
        }
        if ((now.get(Calendar.DAY_OF_MONTH)) < 10) {
            dayOfMonth = "0" + (now.get(Calendar.DAY_OF_MONTH)) + "";
        } else {
            dayOfMonth = (now.get(Calendar.DAY_OF_MONTH)) + "";
        }
        params.put("tableName", this.getTableName());
        String year = now.get(Calendar.YEAR) + "";
        String abbreviation = ShiroKit.getUser().getAbbreviation() + "";
        params.put("medicalRecordNumber", abbreviation.substring(3, abbreviation.length() - 1) + year.substring(2, 4) + month + dayOfMonth);
        int customerCount = dao.getCount(params);
        String customerCounts = customerCount + 1 + "";
        if (customerCount < 10) {
            customerCounts = "00" + customerCounts;
        } else if (customerCount >= 10 && customerCount < 100) {
            customerCounts = "0" + customerCounts;
        } else {
            customerCounts = "" + customerCounts;
        }
        info.setMedicalRecordNumber(abbreviation.substring(3, abbreviation.length() - 1) + year.substring(2, 4) + month + dayOfMonth + customerCounts);
        info.setArrivalStore(ShiroKit.getUser().getOutpatientName());
        String selectSql = "select * from " + this.getTableName() + " where reservations_id='" + info.getReservationsId() + "' limit 0,1";
        CustomerInfo info1 = sqlMapper.selectOne(selectSql, CustomerInfo.class);
        Double actualAccountBalance = 0.00;
        Double giveAccountBalance = 0.00;
        Double accountArrears = 0.00;
        if (info1 != null) {
            actualAccountBalance = info1.getActualAccountBalance();
            giveAccountBalance = info1.getGiveAccountBalance();
            accountArrears = info1.getAccountArrears();
        }
        if (info.getArchiving() == "" || info.getArchiving() == null) {
            info.setArchiving(ShiroKit.getUser().getAccount());
        }
        info.setStatus("到店");
        info.setDiagnosisStatus("未看诊");
        info.setDealStatus("未开单");
        String firstVisitDate = "";
        if (info.getFirstVisitDate() != null && info.getFirstVisitDate() != "") {
            firstVisitDate = "'" + info.getFirstVisitDate() + "'";
        } else {
            firstVisitDate = "null";
        }
        if (info.getAddress() == "" || info.getAddress() == null) {
            info.setAddress("");
        }
        info.setArrivalStore(ShiroKit.getUser().getOutpatientName());
        String sql = "INSERT INTO `" + this.getTableName() + "` (`id`,`diagnosis_status`,`first_visit_date`," +
                "`actual_account_balance`,`give_account_balance`,`account_arrears`,`age_range`,`reservations_id`," +
                "`arrival_store`,`phone_shar_ship`,`deal_status`, `customer_name`, " +
                "`customer_phone`, " +
                "`one_medium`,`two_medium`,`thr_medium`, `one_channel`,`two_channel`,`thr_channel`," +
                " `customer_sex`, `customer_age`, `birthday`," +
                " `address`," + "`customer_status`, " + " `is_return_visit`," +
                " `province`, `cities`, `region`, `medical_record_number`, " +
                " `archiving`, `entry_clerk` ,`update_people`,`filing_time`, xcustomer_status) VALUES" +
                "('" + id + "','未看诊'," + firstVisitDate + "," + actualAccountBalance + "," + giveAccountBalance + "," + accountArrears + ",'"
                + info.getAgeRange() + "','" + info.getReservationsId() + "','"
                + info.getArrivalStore() + "'," + phoneSharShip + ",'" + info.getDealStatus() + "','"
                + info.getCustomerName().trim() +
                "','" + info.getCustomerPhone() + "','" + info.getOneMedium() + "','" + info.getTwoMedium() +
                "','" + info.getThrMedium() + "','" + info.getOneChannel() +
                "','" + info.getTwoChannel() + "','" + info.getThrChannel() +
                "','" + info.getCustomerSex() + "'," + info.getCustomerAge() + "," + birthday +
                ",'" + info.getAddress() + "','预约'," + info.getIsReturnVisit() +
                ",'" + info.getProvince() + "' ,'" + info.getCities() + "','" + info.getRegion() + "','','" +
                info.getArchiving() + "','" + ShiroKit.getUser().getAccount() +
                "','" + ShiroKit.getUser().getAccount() + "' ,'" + info.getFilingTime() + "' ,'" + info.getXcustomerStatus() + "');";
        return sqlMapper.insert(sql) + "," + id;
    }


    public int reconsuling(CustomerInfo info) {
        String id = CommUtils.getUUID();
        String tableHead = ShiroKit.getUser().getAbbreviation();
        id = id + tableHead;
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        id = id + randomNumber;
        String filingTime = "";
        String firstVisitDate = "";
        String birthday = "";
        String auditorTime = "";
        String phoneSharShip = "";
        String starttime = DateTimeKit.now();
        String time = starttime.substring(0, 11);
        int hour = Integer.parseInt(starttime.substring(11, 13));
        int minute = Integer.parseInt(starttime.substring(14, 16));
        minute = (minute / 15) * 15;
        String minutes = minute + "";
        if ("0".equals(minutes)) {
            minutes = "00";
        }
        starttime = time + hour + ":" + minutes + ":00";
        String endtime = "";
        if (hour + 1 == 24) {
            time = time.substring(0, 9) + (Integer.parseInt(time.substring(9, 10)) + 1) + " ";
            endtime = time + "00" + ":" + minutes + ":00";
        } else {
            endtime = time + (hour + 1) + ":" + minutes + ":00";
        }
        if (info.getFilingTime() == null || info.getFilingTime() == "") {
            filingTime = "null";
        } else {
            filingTime = "'" + info.getFilingTime() + "'";
        }
        if (info.getFirstVisitDate() == null || info.getFirstVisitDate() == "") {
            firstVisitDate = "'" + DateTimeKit.now() + "'";
        } else {
            firstVisitDate = "'" + info.getFirstVisitDate() + "'";
        }
        if (info.getPhoneSharShip() == null || info.getPhoneSharShip() == "") {
            phoneSharShip = "'本人'";
        } else {
            phoneSharShip = "'" + info.getPhoneSharShip() + "'";
        }
        if (info.getBirthday() == null || info.getBirthday() == "") {
            birthday = "null";
        } else {
            birthday = "'" + info.getBirthday() + "'";
        }
        if (info.getAuditorTime() == null || info.getAuditorTime() == "") {
            auditorTime = "null";
        } else {
            auditorTime = "'" + info.getAuditorTime() + "'";
        }
        if (info.getCustomerAge() != null) {
            for (int i = 0; i < 11; i++) {
                if (info.getCustomerAge() >= (i * 10) && info.getCustomerAge() <= (i * 10 + 9)) {
                    String ageRange = (i * 10) + "-" + (i * 10 + 9);
                    info.setAgeRange(ageRange);
                }
            }
        }
        Calendar now = Calendar.getInstance();
        Map<String, Object> params = new HashMap<String, Object>();
        String month = "";
        String dayOfMonth = "";
        if ((now.get(Calendar.MONTH) + 1) < 10) {
            month = "0" + (now.get(Calendar.MONTH) + 1);
        } else {
            month = (now.get(Calendar.MONTH) + 1) + "";
        }
        if ((now.get(Calendar.DAY_OF_MONTH)) < 10) {
            dayOfMonth = "0" + (now.get(Calendar.DAY_OF_MONTH)) + "";
        } else {
            dayOfMonth = (now.get(Calendar.DAY_OF_MONTH)) + "";
        }
        String year = now.get(Calendar.YEAR) + "";
        String abbreviation = ShiroKit.getUser().getAbbreviation() + "";
        params.put("medicalRecordNumber", abbreviation.substring(3, abbreviation.length() - 1) + year.substring(2, 3) + month + dayOfMonth);
        params.put("tableName", this.getTableName());
        int customerCount = dao.getCount(params);
        String customerCounts = customerCount + 1 + "";
        if (customerCount < 10) {
            customerCounts = "00" + customerCounts;
        } else if (customerCount >= 10 && customerCount < 100) {
            customerCounts = "0" + customerCounts;
        } else {
            customerCounts = "" + customerCounts;
        }
//        info.setMedicalRecordNumber(ShiroKit.getUser().getOutpatientName() + now.get(Calendar.YEAR) + month + dayOfMonth + customerCounts);
        info.setArrivalStore(ShiroKit.getUser().getOutpatientName());
        info.setStatus("到店");
        info.setDiagnosisStatus("未看诊");
        info.setDealStatus("未开单");
        String selectSql = "select * from " + this.getTableName() + " where reservations_id='" + info.getReservationsId() + "' limit 0,1";
        CustomerInfo info1 = sqlMapper.selectOne(selectSql, CustomerInfo.class);
        Double actualAccountBalance = 0.00;
        Double giveAccountBalance = 0.00;
        Double accountArrears = 0.00;
        if (info1 != null) {
            actualAccountBalance = info1.getActualAccountBalance();
            giveAccountBalance = info1.getGiveAccountBalance();
            accountArrears = info1.getAccountArrears();
        }
        if (info.getDoctor() == "" || info.getDoctor() == null) {
            info.setDoctor("未指定医生");
        }
        if (info.getAddress() == "" || info.getAddress() == null) {
            info.setAddress("");
        }
        if ("null".equals(info.getOtherContact()) || info.getOtherContact() == null) {
            info.setOtherContact("");
        }
       /* if ("再消".equals(info.getXcustomerStatus())) {
            info.setXcustomerStatus("再消");
        }else if ("初到洁牙".equals(info.getXcustomerStatus())||"流失".equals(info.getXcustomerStatus())||"初治".equals(info.getXcustomerStatus())){
            info.setXcustomerStatus("复到");
        }*/
        String sql = "INSERT INTO `" + this.getTableName() + "` (`id`,`doctor`,`first_visit_date`,`actual_account_balance`,`give_account_balance`,`account_arrears`,`age_range`,`reservations_id`,`appointment_pay_service`,`arrival_store`,`phone_shar_ship`,`deal_status`, `customer_name`, `pseudonym`, `customer_phone`, " +
                "`one_medium`,`two_medium`,`thr_medium`, `one_channel`,`two_channel`,`thr_channel`," +
                "`field_tc`, `customer_sex`, `customer_age`, `birthday`," +
                " `address`, `referee`, `referee_ship`, `id_card_no`," +
                " `fixed_telephone`, `is_have_children`, `email`, `zip_code`, " +
                "`customer_status`, `number_of_audits`, `auditor_time`, `final_auditor`," +
                "  `non_transaction_level`, `transaction_level`, `characters`, " +
                "`consumption_habits`, `is_return_visit`, `cause_of_no_return_visit`, `consum_ability`," +
                " `qq_number`, `wechat_number`, `other_contact`, `country`," +
                " `province`, `cities`, `region`, `medical_record_number`, " +
                " `marital_status`, `occupation`, `archiving`, `entry_clerk`,`update_people`,`update_time`," +
                " `filing_time`, `arrival_time`, `remarks`, `status`, `diagnosis_status`, `start_time`, `end_time`, `arrival_status`, " +
                "`create_appointment_time`,xcustomer_status) VALUES" +
                "('" + id + "','" + info.getDoctor() + "'," + firstVisitDate + "," + actualAccountBalance + "," + giveAccountBalance + "," + accountArrears + ",'" + info.getAgeRange() + "','" + info.getReservationsId() + "','" + info.getAppointmentPayService() + "','" + info.getArrivalStore() + "'," + phoneSharShip + ",'" + info.getDealStatus() + "','" + info.getCustomerName().trim() + "','" + info.getPseudonym() +
                "','" + info.getCustomerPhone() + "','" + info.getOneMedium() + "','" + info.getTwoMedium() + "','" + info.getThrMedium() + "','" + info.getOneChannel() + "'" +
                ",'" + info.getTwoChannel() + "','" + info.getThrChannel() + "'" +
                ",'" + info.getFieldTc() + "'," + info.getCustomerSex() + "," + info.getCustomerAge() + "," + birthday +
                ",'" + info.getAddress() + "','" + info.getReferee() + "','" + info.getRefereeShip() + "','" + info.getIdCardNo() +
                "','" + info.getFixedTelephone() + "'," + info.getIsHaveChildren() + "," + "'" + info.getEmail() + "','" + info.getZipCode() +
                "','" + info.getCustomerStatus() + "'," + info.getNumberOfAudits() + "," + auditorTime + ",'" + info.getFinalAuditor() +
                "','" + info.getNonTransactionLevel() + "', '" + info.getTransactionLevel() + "','" + info.getCharacters() +
                "','" + info.getConsumptionHabits() + "'," + info.getIsReturnVisit() + ",'" + info.getCauseOfNoReturnVisit() + "','" + info.getConsumAbility() +
                "','" + info.getQqNumber() + "', '" + info.getWechatNumber() + "','" + info.getOtherContact() + "','" + info.getCountry() +
                "','" + info.getProvince() + "' ,'" + info.getCities() + "','" + info.getRegion() + "','" + info.getMedicalRecordNumber() + "','" + info.getMaritalStatus() + "'," +
                "'" + info.getOccupation() + "','" + info.getArchiving() + "','" + ShiroKit.getUser().getAccount() +
                "','" + ShiroKit.getUser().getAccount() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "','" + DateTimeKit.now() + "" +
                "','" + info.getRemarks() + "','" + info.getStatus() + "','" + info.getDiagnosisStatus() + "','" + starttime + "','" + endtime + "',2,'"
                + DateTimeKit.now() + "','" + info.getXcustomerStatus() + "');";
        return sqlMapper.insert(sql);
    }


    public List<CustomerInfo> getCustomerPhoneCount(CustomerInfo info) {
        String sql = "select id, customer_phone,reservations_id ,medical_record_number from " + this.getTableName() + " where customer_phone ='" + info.getCustomerPhone() + "' and medical_record_number like " +
                "CONCAT('%','" + ShiroKit.getUser().getOutpatientName() + "','%') and phone_shar_ship='" + info.getPhoneSharShip() + "'";
        List<CustomerInfo> infoList = sqlMapper.selectList(sql, CustomerInfo.class);
        return infoList;
    }

    public List<CustomerInfo> getUpdatePhoneCount(String customerPhone, String id) {
        String sql = "select id, customer_phone,reservations_id,medical_record_number from " + this.getTableName() + " where id !='" + id + "' and customer_phone='" + customerPhone + "' and phone_shar_ship='';";
        List<CustomerInfo> infoList = sqlMapper.selectList(sql, CustomerInfo.class);
        return infoList;
    }

    @Transactional
    public void delete(String id) {
        CustomerInfo customerInfo = this.selectOneById(id);
        String deleteSql = "delete from reservations_info where id='" + customerInfo.getReservationsId() + "';";
        String sql = "delete from " + this.getTableName() + "  where id = '" + id + "'";
        sqlMapper.delete(sql);
    }

    public int toVoid(CustomerInfo customerInfo) {
        String deleteSql = " update reservations_info where id='" + customerInfo.getReservationsId() + "';";
        String sql = "update " + this.getTableName() + " set customer_status='作废' , to_void_remarks='" + customerInfo.getToVoidremarks() + "'" +
                ", to_void_people='" + ShiroKit.getUser().getAccount() + "',to_void_time='" + DateTimeKit.now() + "' where id = '" + customerInfo.getId() + "'";
        return sqlMapper.update(sql);
    }


    @Transactional
    public void updateReservation(String rservationsId) {
        String selectsql = "select " +
                "  (CASE a.customer_sex  " +
                "  WHEN 1 THEN  " +
                "  '男'  " +
                "  WHEN 2 THEN  " +
                "  '女'  " +
                "  ELSE  " +
                "  '未知'  " +
                "  END  " +
                " ) as sex ,a.* from reservations_info a where id= '" + rservationsId + "' limit 0,1";
        ReservationsInfo reservations = sqlMapper.selectOne(selectsql, ReservationsInfo.class);
        if (reservations != null) {
            if (StringUtil.isEmpty(reservations.getFirstVisitDate())) {
                String sql1 = "update reservations_info set status='到店' ,first_visit_date='" + DateTimeKit.now() + "',identification_number='" + reservations.getIdentificationNumber() + "'  where id = '" + rservationsId + "'";
                sqlMapper.update(sql1);
            } else {
                String sql1 = "update reservations_info set status='到店',identification_number='" + reservations.getIdentificationNumber() + "'  where id = '" + rservationsId + "'";
                sqlMapper.update(sql1);
            }
        }
    }

    public int update(CustomerInfo info) {
        String filingTime = "";
        String birthday = "";
        String auditorTime = "";
        if (info.getFilingTime() == null || info.getFilingTime() == "") {
            filingTime = "null";
        } else {
            filingTime = "'" + info.getFilingTime() + "'";
        }
        if (info.getBirthday() == null || info.getBirthday() == "") {
            birthday = "null";
        } else {
            birthday = "'" + info.getBirthday() + "'";
        }
        if (info.getAuditorTime() == null || info.getAuditorTime() == "") {
            auditorTime = "null";
        } else {
            auditorTime = "'" + info.getAuditorTime() + "'";
        }
        if (info.getCustomerAge() != null) {
            for (int i = 0; i < 11; i++) {
                if (info.getCustomerAge() >= (i * 10) && info.getCustomerAge() <= (i * 10 + 9)) {
                    if (i < 10) {
                        String ageRange = (i * 10) + "-" + (i * 10 + 9);
                        info.setAgeRange(ageRange);
                    } else {
                        String ageRange = "99+";
                        info.setAgeRange(ageRange);
                    }
                }
            }
        }
        Calendar now = Calendar.getInstance();
        Map<String, Object> params = new HashMap<String, Object>();
        String month = "";
        String dayOfMonth = "";
        if ((now.get(Calendar.MONTH) + 1) < 10) {
            month = "0" + (now.get(Calendar.MONTH) + 1);
        } else {
            month = (now.get(Calendar.MONTH) + 1) + "";
        }
        if ((now.get(Calendar.DAY_OF_MONTH)) < 10) {
            dayOfMonth = "0" + (now.get(Calendar.DAY_OF_MONTH)) + "";
        } else {
            dayOfMonth = (now.get(Calendar.DAY_OF_MONTH)) + "";
        }
        String year = now.get(Calendar.YEAR) + "";
        String abbreviation = ShiroKit.getUser().getAbbreviation() + "";
        params.put("medicalRecordNumber", abbreviation.substring(3, abbreviation.length() - 1) + year.substring(2, 3) + month + dayOfMonth);
        params.put("tableName", this.getTableName());
        int customerCount = dao.getCount(params);
        String customerCounts = customerCount + 1 + "";
        if (customerCount < 10) {
            customerCounts = "00" + customerCounts;
        } else if (customerCount >= 10 && customerCount < 100) {
            customerCounts = "0" + customerCounts;
        } else {
            customerCounts = "" + customerCounts;
        }
        if (info.getAddress() == "" || info.getAddress() == null) {
            info.setAddress("");
        }
        String sql = "UPDATE " + this.getTableName() + "  SET customer_name='" + info.getCustomerName().trim() + "', customer_phone='"
                + info.getCustomerPhone() + "',  field_tc='" + info.getFieldTc() + "'," +
                " `age_range`='" + info.getAgeRange() + "', customer_sex='" + info.getCustomerSex() + "',`phone_shar_ship`='" + info.getPhoneSharShip()
                + "',  customer_age=" + info.getCustomerAge() + ",  birthday=" + birthday + "," +
                " is_have_children=" + info.getIsHaveChildren() + ", is_return_visit=" + info.getIsReturnVisit() + ", customer_status='"
                + info.getCustomerStatus() + "',medical_record_number='" + info.getMedicalRecordNumber() + "', number_of_audits="
                + info.getNumberOfAudits() + ", auditor_time=" + auditorTime + ",  consum_ability='" + info.getConsumAbility() + "', " +
                " qq_number='" + info.getQqNumber() + "',  wechat_number='" + info.getWechatNumber() + "', " +
                " one_medium='" + info.getOneMedium() + "',two_medium='" + info.getTwoMedium() + "',thr_medium='" + info.getThrMedium() + "'," +
                " one_channel='" + info.getOneChannel() + "',two_channel='" + info.getTwoChannel() + "',thr_channel='" + info.getThrChannel() + "'," +
                " address='" + info.getAddress() + "',  marital_status=" + info.getMaritalStatus() + ",  occupation='" + info.getOccupation() + "' , " +
                " reservations_id='" + info.getReservationsId() + "', appointment_pay_service='" + info.getAppointmentPayService()
                + "', update_people='" + ShiroKit.getUser().getAccount() + "',update_time='" + DateTimeKit.now()
                + "', remarks='" + info.getRemarks() +
                "' WHERE id='" + info.getId() + "' ";
        return sqlMapper.update(sql);
    }


    public List<CustomerInfo> selectOneByCp(String customerPhone) {
        String sql = " select a.id,a.reservations_id,a.customer_status,a.medical_record_number,a.customer_name,a.customer_phone,a.phone_shar_ship, " +
                "     (\n" +
                "        CASE a.customer_sex\n" +
                "        WHEN 1 THEN\n" +
                "            '男'\n" +
                "        WHEN 2 THEN\n" +
                "            '女'\n" +
                "        ELSE\n" +
                "            '未知'\n" +
                "        END\n" +
                "    ) as sex , a.customer_age,a.arrival_status " +
                " from " + this.getTableName() + " a where a.customer_phone like CONCAT('%','" + customerPhone + "','%') and arrival_store='" + ShiroKit.getUser().getOutpatientName() + "' group by  a.reservations_id;";
        List<CustomerInfo> list = sqlMapper.selectList(sql, CustomerInfo.class);
        for (CustomerInfo info : list) {
            info.setCustomerStatus(this.getCustomerStatus(info));
        }
        return list;
    }

    public List<CustomerInfo> selectOneByCps(String customerPhone) {
        String sql = "SELECT * from ( select a.id,a.reservations_id as reservationsId,a.customer_status,a.medical_record_number,a.customer_name,a.customer_phone,a.phone_shar_ship, " +
                "     (\n" +
                "        CASE a.customer_sex\n" +
                "        WHEN 1 THEN\n" +
                "            '男'\n" +
                "        WHEN 2 THEN\n" +
                "            '女'\n" +
                "        ELSE\n" +
                "            '未知'\n" +
                "        END\n" +
                "    ) as sex , a.customer_age,a.arrival_status " +
                " from " + this.getTableName() + " a where a.customer_phone like CONCAT('%','" + customerPhone + "','%') and left(start_time,10)='" + DateTimeKit.now().substring(0, 10) + "' and arrival_status=1 ORDER BY start_time)t group by t.reservationsId;";
        List<CustomerInfo> list = sqlMapper.selectList(sql, CustomerInfo.class);
        for (CustomerInfo info : list) {
            info.setCustomerStatus(this.getCustomerStatus(info));
        }
        return list;
    }

    public String getTableName() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return tableName;
    }

}
